<?php

namespace app\model\table;

use app\model\BaseModel;
use function think\p;

class Ip extends BaseModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'app_ip';

    // 该表是否缓存到redis
    public $tableToRedis = true;

    // 该表是否允许全表缓存到单个redis
    public $tableListToRedis = false;

    // 该表缓存到redis的策略
    public $tableToRedisKey = ['ip'];

    // 不允许通过add方法修改的字段
    //public $notAllowAddColumn = [];

    public $joinWithList = array(
    );

    /**
     * 获取ip的地址
     * @param $ip
     * @return mixed|string
     */
    public function getAddress($ip)
    {
        $obj = self::instance()->findOne(['ip'=>$ip], true);
        if(empty($obj)){
            $addressInfo = $this->getIpAddress($ip);
            if(!empty($addressInfo)){
                $postData = array(
                    'ip' => $ip,
                    'address' => $addressInfo['nation'],
                    'province' => $addressInfo['province'],
                    'city' => $addressInfo['city'],
                    'proCode' => $addressInfo['proCode']??'',
                    'cityCode' => $addressInfo['cityCode']??'',
                    'nation' => $addressInfo['nation']??'',
                    'created_at' => date("Y-m-d H:i:s", time()),
                );
                self::instance()->addOne($postData);
                return $addressInfo['nation'];
            }
        }else{
            // ip地址是会变的，所以最多保存90天，在下一次使用的时候重新获取
            if( time() - strtotime($obj['created_at']) > 86400 * 90 ){
                $selfObj = Ip::instance()->findOne(['ip'=>$ip], true);
                Ip::instance()->delOne($selfObj['id']);
                return $this->getAddress($ip);
            }else{
                return $obj['nation'];
            }
        }
    }

//    public function getIpAddress($ip)
//    {
//        if(empty($ip)){
//            return "";
//        }
//        $url = 'http://api.map.baidu.com/location/ip?ak=Q2z2op151ksT4PB2Aw3cDYML40Gu7A5K&ip=' . $ip;
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//        $data = curl_exec($ch);
//        curl_close($ch);
//        $data = json_decode($data,true);
//        return $data['content']['address'];
//    }

    /**
     * 获取ip归属地
     * @param $ip
     * @return mixed|string
     */
    public function getIpAddress($ip)
    {
        if(empty($ip)){
            return "";
        }
        $host = "https://qryip.market.alicloudapi.com";
        $path = "/lundear/qryip";
        $method = "GET";
        $appcode = "3db4ef1d4fea4bacb868679993e4eb06";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "ip=".$ip;
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $data = curl_exec($curl);
        $data = json_decode($data,true);
        if($data['status'] == 0){
            return $data['result']['ad_info'];
        }else{
            return "";
        }
    }
}
